<template>
  <ql-dialog
    :title="props.roleId ? '编辑角色' : '添加角色'"
    :confirm="confirm"
    @open="handleDialogOpen"
    @closed="handleDialogClosed"
  >
    <el-form
      ref="form"
      v-loading="formLoading"
      label-width="100px"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item
        label="角色名称："
        prop="roleName"
      >
        <el-input
          v-model="formData.roleName"
          placeholder="请输入角色名称"
        />
      </el-form-item>
      <el-form-item label="备注信息：">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注"
        />
      </el-form-item>
      <el-form-item label="角色权限：">
        <el-tree
          ref="tree"
          :default-checked-keys="[1]"
          node-key="menuId"
          show-checkbox
          check-strictly
          default-expand-all
          :data="menus"
          :props="{
            label: 'name',
            disabled: 'disabled'
          }"
        />
      </el-form-item>
    </el-form>
  </ql-dialog>
</template>

<script setup>
import { roleInfo, menuNav, roleSave, roleUpdate } from '@/api/setting/role'
// import menusData from '@/store/modules/menus' // 模拟菜单树

const props = defineProps({
  roleId: { // 编辑的管理员 ID
    type: Number,
    default: null
  }
})
const emit = defineEmits(['success', 'update:role-id'])

const formData = ref({
  roleName: '',
  remark: '',
  menuIdList: []
})
const formRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ]
}

// 获取数据
const formLoading = ref(false)
const handleDialogOpen = async () => {
  formLoading.value = true
  await loadMenus().finally(() => {
    formLoading.value = false
  })
}

// 获取菜单树
const menus = ref([])
const loadMenus = async () => {
  const data = await menuNav()
  data.forEach((item) => {
    if (item.menuId === 1) {
      item.disabled = true
    }
  })
  menus.value = data
  await nextTick() // 菜单树渲染完成后处理后面的操作
  await loadRole()
}

// 获取角色对应菜单
const tree = ref(null)
const loadRole = async () => {
  if (!props.roleId) return
  const data = await roleInfo(props.roleId)
  formData.value = data
  tree.value.setCheckedKeys(data.menuIdList)
}

// 保存
const form = ref(null)
const confirm = async () => {
  const valid = await form.value?.validate()
  if (!valid) return
  formData.value.menuIdList = [
    ...tree.value?.getCheckedKeys() || [],
    ...tree.value?.getHalfCheckedKeys() || []
  ]

  props.roleId ? await roleUpdate(formData.value) : await roleSave(formData.value)
  emit('success')
  ElMessage.success('保存成功')
}

// 关闭弹框
const handleDialogClosed = () => {
  emit('update:role-id', null)
  menus.value = []
  form.value?.resetFields() // 清除表单数据
}
</script>

<style scoped lang='scss'>

</style>
